package com.dbapp.config;


import com.dbapp.common.user.interceptor.CommonUserInterceptor;
import com.dbapp.common.user.service.SsoHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * @author
 * @Description
 * @date 2021/6/21 10:08
 */
@Configuration
public class WebSecurityConfig implements WebMvcConfigurer {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${common-user.interceptor.reference}")
    private String interceptorClassReference;

    @Value("${common-user.interceptor.excludeUrls}")
    private String excludeUrls;
    @Value("${common-user.interceptor.domain}")
    private String domain;
    @Value("${common-user.interceptor.loginUrl}")
    private String loginUrl;
    @Value("${server.servlet.context-path}")
    private String cookiePath;

    @Autowired
    private Environment environment;

    /**
     * 配置拦截规则与注入拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // addPathPattern 添加拦截规则 /** 拦截所有包括静态资源
        // excludePathPattern 排除拦截规则 所以我们需要放开静态资源的拦截
        registry.addInterceptor(loginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/")
                .excludePathPatterns("/login/login")
                .excludePathPatterns("classpath:/META-INF/resources/")
                .excludePathPatterns("/swagger-ui.html","/swagger-resources","/doc.html","/v2/api-docs","/swagger-resources/configuration/ui","/favicon.ico","/error")
                .excludePathPatterns("/css/**","/fonts/**","/images/**","/js/**")
                .excludePathPatterns("/webjars/**");
    }

    @Bean //将自定义拦截器注册到spring bean中
    public HandlerInterceptor loginInterceptor(){
        List<String> urls = new ArrayList<String>();
        if (excludeUrls != null && excludeUrls.length() > 0) {
            String str = ",";
            for (String s : excludeUrls.split(str)) {
                if (s != null && s.length() > 0) {
                    urls.add(s.trim());
                }
            }
        }
        return new CommonUserInterceptor(urls, interceptorClassReference, loginUrl);
    }

    @Bean
    public SsoHandler getSsoHandler() {
        SsoHandler ssoHandler = null;
        try {
            ssoHandler = (SsoHandler) Class.forName(interceptorClassReference).newInstance();
        } catch (ClassNotFoundException e) {
            logger.error(String.format("Not found interface UserValidateFilter implements: %s ", this.interceptorClassReference), e);
            System.exit(1);
        } catch (InstantiationException | IllegalAccessException e) {
            logger.error(String.format("init interface UserValidateFilter implements: %s ", this.interceptorClassReference), e);
            System.exit(1);
        }
        return ssoHandler;
    }

}
